<template>
  <!-- <el-select v-model="sval" clearable placeholder="请选择地块分组" :style="{width}" @change="onChcange" class="small-el-input__inner" popper-class="samll-el-select-dropdown__list">
        <el-option v-for="dt in lists" :key="dt.stageTaskId" :value="dt.stageTaskId" :label="dt.taskName" />
    </el-select> -->
  <el-cascader
    v-model="sval"
    :options="options"
    placeholder="请选择地块"
    :props="cascaderProps"
    :show-all-levels="false"
    :style="{width}"
    collapse-tags
    collapse-tags-tooltip
    :max-collapse-tags="3"
    clearable
    @change="handleChange"
  />
</template>
<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { getLandGroupList, getLandList } from '@/api/plant'
import { useUserStore } from '@/pinia/modules/user'

const userStore = useUserStore()

const props = defineProps({
  modelValue: '',
  width: {
    type: String,
    // default:'100%'
  },
  params: { // 查询条件
    type: Object,
    default: {}
  },
  keyName: '', // 返回的属性名对应的值
  multiple: { // 查询条件
    type: Boolean,
    default: false
  },
  selectLandsId: {
    type: Array,
    default: []
  }
})
const emit = defineEmits(['update:modelValue', 'change', 'complete'])
const sval = ref([])
const lists = ref('')
const cascaderProps = ref({
  value: 'farmLandId',
  label: 'farmLandName',
  multiple: props.multiple,
})
const options = ref([])

onMounted(async() => {
  console.log(props.selectLandsId.value, '------------01')
  sval.value = props.selectLandsId.value
  // const res = await getLandGroupList({page: 1, limit: 1000000})
  // options.value = [...res.data]
  // // 查找每个分组下的地块
  // options.value.forEach(async item =>{
  //     // 给每个分组数据添加2个字段（只有同一了才能在cascader中显示）
  //     item.farmLandId = item.landGroupId
  //     item.farmLandName = item.groupName

  //     const res2 = await getLandList({landGroupId:item.landGroupId,limit:1000000,page:1})
  //     if(res2.data && res2.data.length>0){
  //         item.children = res2.data
  //     }
  // })

  // 获取公司所有地块
  const res = await getLandList({
    limit: 1000000,
    page: 1,
    companyId: userStore.userInfo.companyId
  })

  if (res.data && res.data.length > 0) {
    for (let i = 0; i < res.data.length; i++) {
      const item = res.data[i]
      const fIndex = options.value.findIndex(ele => ele.landGroupId == item.landGroupId)

      if (fIndex > -1) {
        options.value[fIndex].children.push(item)
      } else {
        const groupItem = {
          landGroupId: item.landGroupId,
          groupName: item.groupName,
          children: [item],
          // 而外添加2个字段（只有统一了才能在cascader中显示）
          farmLandId: item.landGroupId,
          farmLandName: item.groupName,

        }
        options.value.push(groupItem)
      }
    }
  }
  await nextTick()
  emit('complete')
})

watch(() => props.modelValue, (n, o) => {
  sval.value = n
})

const handleChange = () => {
  // console.log("选择值：",sval.value)
  const selectData = []
  sval.value.forEach(item => {
    // 查找选择的当前组
    const curGroup = JSON.parse(JSON.stringify(options.value.find(ele => ele.landGroupId == item[0])))
    // 查找选择的当前地块
    const curLand = curGroup.children.find(ele => ele.farmLandId == item[1])

    // 删除之前组装的属性
    delete curGroup.farmLandId
    delete curGroup.farmLandName
    delete curGroup.children

    selectData.push({ curGroup, curLand })
  })
  // console.log("选择整体值：",selectData)
  emit('update:modelValue', sval.value)
  emit('change', selectData)
}

const setDisabledItem = (selectedList) => {
  // console.log("TTTTTTTTTTTTTTTTTT:",selectedList)
  const landIds = []
  // 循环取出已经选择的地块id，放入landIds中
  selectedList.forEach(item => {
    landIds.push(parseInt(item.curLand.farmLandId))
  })
  // console.log("所选择的地块id数组：",landIds)
  forArrToAddProp(options.value, landIds)
}

const forArrToAddProp = (arr, params) => {
  // 设置某一项为禁用，在该项添加属性disabled: true,
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i]
    if (item.farmLandId && params.indexOf(item.farmLandId) > -1) { // 说明已经选择了
      item.disabled = true // 添加属性，使其该项为禁用
    } else {
      item.disabled = false
    }
    if (item.children) {
      forArrToAddProp(item.children, params)
    }
  }
}

defineExpose({ setDisabledItem })

// const getTableData = async () => {
//   const res = await getTaskList({ page: 1, limit: 100,...props.params})
//   if (res.code == 0) {
//     lists.value = res.data
//     //console.log("GGGGG:",props)
//     sval.value = props.modelValue || '' // 设置默认选项
//   }
// }

const onChcange = () => {
  if (props.keyName) {
    const item = lists.value.find(ele => ele.id == sval.value)
    emit('update:modelValue', item[props.keyName])
    emit('change', sval.value)
  } else {
    emit('update:modelValue', sval.value)
    emit('change', sval.value)
  }
}

</script>

<style scoped lang="scss">
</style>
